import React from 'react';
import FileUpload from './FileUpload';
import {IMAGE} from './types';
import utils from '../../../utils';

import {WeaLocaleProvider} from "ecCom";
import fillin from "../../../apis/fillin";

const getLabel = WeaLocaleProvider.getLabel;

export default class ImgUpload extends React.Component {
  static defaultProps = {
    iswx: false,
    onChange: () => { }
  };

  constructor(props) {
    super();

    this.state = {
      iswx: props.iswx,
      files: props.iswx ? [] : null
    };
  }

  componentWillMount(){
    const {files} = this.props;
    (files && files.length > 0) && (this.state.files = files);
  }

  componentWillReceiveProps(nextProps) {
    if('iswx' in nextProps) {
      this.setState({ iswx: nextProps.iswx });
    }
  }

  getContent(maxNum) {
    return (
      <div className='wea-edc-upload-img-content'>
        <div className='img-placeholder'>
          <i className='icon-edc-app-plus-circle-fill' />
        </div>
        <div>{getLabel('502261','选择图片') }</div>
        <p>{
          maxNum ?
            `(`+ getLabel('503776','数量最多$s个').replace(/\$s/, maxNum) + `)`
            : ''
        }</p>
      </div>
    );
  }

  chooseImage = () => {
    const wx = window.wx;
    const { maxNum,onUploading } = this.props;
    const { files } = this.state;

    if(!wx) return;

    wx.ready(() => {
      wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        count: maxNum - files.length > 0 ? maxNum - files.length : 0, // 最多可以选择的图片张数，默认9

        success: res => {
          let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片

          if(files.length >= maxNum) return;
          localIds = [...localIds].slice(0, this.props.maxNum - files.length);

          localIds.forEach(localId => {
            const newFile = {
              localId,
              id: utils.UUID(),
              img: localId,
              docid: -1,
              uploading: false,
              uploadPercent: 0
            };

            files.push(newFile);
            wx.getLocalImgData({
              localId,
              success: res => {
                onUploading(true);
                const localData = res.localData.split(',');
                const [ base64Str, base64Img ] = localData;

                newFile.img = 'data:image/jpg;base64,' + (base64Img || base64Str); // localData是图片的base64数据
                newFile.uploading = true;
                newFile.uploadPercent = 5;
                this.setState({ files });

                this.uploadImgData(newFile, newFile.img);
              }
            });
          });
          this.setState({ files });
          this.props.onChange(files);
        }
      });
    });
  }

  uploadImgData(file, imgData) {
    const {onUploading} = this.props;
    const {files} = this.state;
    const mime_type = "image/jpeg";

    const _changeState = files => {
      this.setState({files});
    };

    const _changeVal = files => {
      this.props.onChange(files);
    };

    let formData = new FormData();
    formData.append("file", imgData);
    formData.append("type", "base64");

    formData.append("fileType", mime_type);

    file.uploadPercent = 10;
    _changeState(files);

    fillin.uploadFile(formData).then((res) => {
      if (res.docid) {
        file.docid = res.docid;

        setTimeout(function () {
          file.uploadPercent = 100;
          _changeState(files);

        }, 500);
        setTimeout(function () {
          onUploading(false);
          file.uploading = false;
          _changeState(files);
          _changeVal(files);
        }, 800);

      }
    }).catch((e) => {
      onUploading(false);
      console.log(e);
    });

    setTimeout(function () {
      file.uploadPercent = 50;
      _changeState(files);
    }, 500);
  }

  previewImage = fileId => {
    const wx = window.wx;

    if (!wx) return;

    wx.ready(() => {
      const {files} = this.state;
      const file = files.find(({id}) => fileId === id);

      if (!file) return;

      wx.previewImage({
        current: file.localId,
        urls: [file.localId]
      });
    });
  }

  render() {
    const { iswx, files } = this.state;
    const { maxNum, onChange, onUploading } = this.props;

    return (
      <FileUpload
        accept={IMAGE}
        maxNum={maxNum}
        files={files}
        className='wea-edc-upload-img'
        maxSize={200 * 1024 * 1024}
        content={this.getContent(maxNum)}
        disableClick={iswx}
        onClick={this.chooseImage}
        onFileItemClick={iswx ? this.previewImage : null}
        onChange={onChange}
        onUploading={onUploading}
      />
    )
  }
};